package daemon

import (
	"fmt"
	"path/filepath"
	"time"

	"go.uber.org/zap"
	"gitee.com/liumou_site/ssh-go-automatic-upgrade/internal/downloader"
	"gitee.com/liumou_site/ssh-go-automatic-upgrade/internal/installer"
	"gitee.com/liumou_site/ssh-go-automatic-upgrade/internal/version"
)

// UpgradeService SSH升级服务
type UpgradeService struct {
	mirror        string
	installDir    string
	downloadDir   string
	force         bool
	skipTLSVerify bool
}

// NewUpgradeService 创建升级服务
func NewUpgradeService(mirror, installDir, downloadDir string, force, skipTLSVerify bool) *UpgradeService {
	return &UpgradeService{
		mirror:        mirror,
		installDir:    installDir,
		downloadDir:   downloadDir,
		force:         force,
		skipTLSVerify: skipTLSVerify,
	}
}

// CheckAndUpgrade 检查并升级SSH
func (us *UpgradeService) CheckAndUpgrade() error {
	zap.L().Info("开始检查SSH升级")

	// 创建版本检测器
	detector := version.NewDetector(us.mirror, us.skipTLSVerify)

	// 检查当前系统版本
	currentVersion, err := detector.CheckCurrentVersion()
	if err != nil {
		zap.L().Error("检查当前SSH版本失败", zap.Error(err))
		return fmt.Errorf("检查当前版本失败: %v", err)
	}

	zap.L().Info("当前SSH版本", zap.String("currentVersion", currentVersion))

	// 检查最新版本
	latestVersionInfo, err := detector.GetLatestVersion()
	if err != nil {
		zap.L().Error("获取最新SSH版本失败", zap.Error(err))
		return fmt.Errorf("获取最新版本失败: %v", err)
	}

	zap.L().Info("最新SSH版本", zap.String("latestVersion", latestVersionInfo.Version))

	// 比较版本
	if currentVersion == latestVersionInfo.Version && !us.force {
		zap.L().Info("当前已是最新版本，无需升级")
		return nil
	}

	zap.L().Info("发现新版本", zap.String("currentVersion", currentVersion), zap.String("latestVersion", latestVersionInfo.Version))

	// 执行升级流程
	if err := us.performUpgrade(latestVersionInfo); err != nil {
		zap.L().Error("SSH升级失败", zap.Error(err))
		return fmt.Errorf("升级失败: %v", err)
	}

	zap.L().Info("SSH升级成功")
	return nil
}

// performUpgrade 执行升级流程
func (us *UpgradeService) performUpgrade(versionInfo *version.VersionInfo) error {
	zap.L().Info("开始执行SSH升级流程")

	// 创建下载器
	downloader := downloader.NewDownloader(us.downloadDir, us.skipTLSVerify)

	// 下载SSH源码包
	downloadedFile := filepath.Join(us.downloadDir, versionInfo.Filename)
	if err := downloader.DownloadFile(versionInfo.DownloadURL, versionInfo.Filename); err != nil {
		return fmt.Errorf("下载SSH源码包失败: %v", err)
	}

	zap.L().Info("SSH源码包下载完成", zap.String("downloadedFile", downloadedFile))

	// 创建安装器
	installer := installer.NewInstaller(us.installDir)

	// 安装OpenSSH
	if err := installer.InstallOpenSSH(downloadedFile); err != nil {
		return fmt.Errorf("安装OpenSSH失败: %v", err)
	}

	zap.L().Info("OpenSSH安装完成")
	return nil
}

// GetUpgradeResult 获取升级结果信息
func (us *UpgradeService) GetUpgradeResult(result string, details string) string {
	checkTime := time.Now().Format("2006-01-02 15:04:05")
	return fmt.Sprintf("[%s] %s: %s", checkTime, result, details)
}

// GetServiceConfig 获取服务配置
func (us *UpgradeService) GetServiceConfig() map[string]interface{} {
	return map[string]interface{}{
		"mirror":       us.mirror,
		"install_dir":  us.installDir,
		"download_dir": us.downloadDir,
		"force":        us.force,
	}
}